/**
 * 
 */
package com.vector.ding.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.DispatcherServlet;

import com.vector.ding.commons.Constant;
import com.vector.ding.context.AuthContext;
import com.vector.ding.context.WebContext;

/**
 * @author vector
 *
 */
public class CustomDispatcherServlet extends DispatcherServlet {
	
	private static final Logger logger = LoggerFactory.getLogger(CustomDispatcherServlet.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.DispatcherServlet#doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doService(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		if (loginAction(request, response)) {
			super.doService(request, response);
			return ;
		}
			
		// check user whether login, if no, jump to login page
		try {
			AuthContext.getCurrentUser();
			super.doService(request, response);
		} catch (Exception e) {
			logger.debug(e.getMessage());
			e.printStackTrace();
			response.sendRedirect(WebContext.getContextPath());
		}
		
	}
	
	/**
	 * weather login action
	 * @param request
	 * @param response
	 * @return
	 */
	private boolean loginAction(HttpServletRequest request, HttpServletResponse response) {
		String uri = request.getRequestURI();
		if (uri.endsWith("/"))
			uri = uri.substring(0, uri.length() - 1);
		if (uri.equals(WebContext.getContextPath()))
			return true;
		if (uri.equals(WebContext.getContextPath() + "/" + Constant.LOGIN_URL))
			return true;
		
		return false;
	}

}
